from django.shortcuts import render
import json
from django.http import HttpResponse,JsonResponse
# 导入django内置用户表
from django.contrib.auth.models import User
from django.views.generic.base import TemplateView            # 导入模板视图
# token配置
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate, get_user_model


# Create your views here.
# 用户登入页面跳转函数
def login(request):
    return render(request, 'login.html')

# 用户注册页面跳转函数
def logout(request):
    return render(request, 'register.html')

# 登入成功后返回的个人中心页面
def loginsuss(request):
    return render(request, 'loginsuss.html')
# 购物车查询api
def requestcar(request):
    pass

def order(request):
    pass

# 注册处理函数
def register(request):
    if request.method == 'POST':
        # 解析JSON数据
        data = json.loads(request.body)
        username = data.get('username', 'unknown')
        password = data.get('password', 'unknown')
        email = data.get('email', 'unknown')
        firstName = data.get('firstName', 'unknown')
        lastName = data.get('lastName', 'unknown')
        phone = data.get('phone', 'unknown')

        print(f"收到注册请求 - 用户名: {username}, "
              f"密码: {password}"
              f"email: {email}, "
              f"firstName: {firstName}, "
              f"lastName: {lastName}, "
              f"phone: {phone}")

        # 注册业务处理
        # 判断用户是否注册
        username_bool = User.objects.filter(username=username).exists()
        # phone = User.objects.filter(phone=phone).exists()
        if username_bool:
            return JsonResponse({
                "success": False,
                "message": "用户名已存在",
            },
                status=400
            )
        # if phone:
        #     return JsonResponse({
        #         "success": False,
        #         "message": "手机号已被注册",
        #     },
        #         status=400
        #     )
        user = User.objects.create_user(
            username=username,
            email=email,
            password=password,
            first_name=firstName,
            last_name=lastName,
        )
        user.save()
        return JsonResponse({
            "success": True,
            "message": "注册成功"
        },
        status=200
        )

# 登入函数处理
def login_1(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username', '')
        password = data.get('password', '')

        # 使用 authenticate 函数一步完成用户查找和密码校验
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # 认证成功，生成 Token
            refresh = RefreshToken.for_user(user)

            # 构建用户信息对象
            user_info = {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'first_name': user.first_name,
                'last_name': user.last_name,
            }

            # 返回前端期望的数据结构
            return JsonResponse({
                "token": str(refresh.access_token),  # Access Token
                "refreshToken": str(refresh),        # Refresh Token
                "user": user_info,
                "message": "登录成功！"
            }, status=200)

        else:
            # 认证失败（用户名不存在或密码错误）
            return JsonResponse({
                "message": "用户名或密码错误"
            }, status=401)